import Cookies from 'js-cookie';
import { login } from '@/api/teacher';
import { 
  getToken, setToken, removeToken, 
  getTeacherID, setTeacherID, removeTeacherID,
  getTeacherName, setTeacherName, removeTeacherName,
  getTeacherMobile, setTeacherMobile, removeTeacherMobile,
} from '@/utils/auth';
import { Message } from 'element-ui';

const user = {
  state: {
    unread: 0,
    token: getToken(),
    teacherid: getTeacherID(),
    teachername: getTeacherName(),
    teachermobile: getTeacherMobile(),
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token;
    },
    SET_TEACHERID: (state, teacherid) => {
      state.teacherid = teacherid;
    },
    SET_TEACHERNAME: (state, teachername) => {
      state.teachername = teachername;
    },
    SET_TEACHERMOBILE: (state, teachermobile) => {
      state.teachermobile = teachermobile;
    },
  },

  actions: {
    Login({ commit },userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          if (response.code==0){
            let data = response.data;
            setToken(data.Token);
            commit('SET_TOKEN', data.Token);
            setTeacherID(data.TeacherDataID);
            commit('SET_TEACHERID', data.TeacherDataID);
            setTeacherName(data.TeacherName);
            commit('SET_TEACHERNAME', data.TeacherName);
            setTeacherMobile(data.UserMobile);
            commit('SET_TEACHERMOBILE', data.UserMobile);
            resolve();
          }
          else{
            Message.error(response.msg);
            reject();
          }
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 登出{ state }
    LogOut({ commit, state}) {
      return new Promise((resolve, reject) => {
        removeToken();
        removeTeacherID();
        removeTeacherName();
        removeTeacherMobile();
        resolve();
      });
    },
  }
};

export default user;
